package atguigu.demo3

import scala.collection.mutable.ArrayBuffer

/**
  * Created by lzd on 2018/10/30.
  * 数组操作
  */
object demo3_2 {
  def main(args: Array[String]): Unit = {
    val a = Array(2, 3, 5, 7, 11)

    //用推导式产生新的数组(可变ArrayBuffer)
    val result = for (item <- a) yield item * 2
    println(result.toBuffer)

    val result1 = for (item <- a; if item % 2 == 0) yield item * 2
    println(result1.toBuffer)

    val result2 = a.filter(_ % 2 == 0).map(_ * 2)
    println(result2.toBuffer)

    //求和
    println(ArrayBuffer(1, 7, 3, 9).sum)
    //求最大值
    println(ArrayBuffer(1, 9, 7, 3).max)

    //排序
    val b = ArrayBuffer(1, 7, 2, 9)
    val bSorted = b.sorted
    println(bSorted)

    val a1 = Array(1, 7, 2, 9)
    scala.util.Sorting.quickSort(a1)
    println(a1.toBuffer)

    // 形成String(1 and 2 and 7 and 9)(<1,2,7,9>)
    println(a1.mkString(" and "))
    println(a1.mkString("<", ",", ">"))

    // 更多方法
    val a2 = Array(1, -2, 3, -4, 5)
    val b2 = ArrayBuffer(1, 7, 2, 9)

    // 统计大于0的个数
    println(a2.count(_ > 0))

    //
    b2.append(1, 7, 2, 8)
    println(b2)


    b2.appendAll(a2)
    println(b2)

    //在数组最后加4，从开头找到7移除
    b2 += 4 -= 7

    println(b2)
    //从数组开头往后找，找到第一个0删掉，再最后加上6
    b2 -= 0 += 6
    println(b2)

    //将b2中的数据copy到a2中，a2的空间为5
    b2.copyToArray(a2)
    println(a2.toBuffer)

    val xs = Array(1, "Fred", 2, 9)
    b2.copyToArray(xs)
    println(xs.toBuffer)

    println(b2)
    // 加到20项，用-1填充
    println(b2.padTo(20, -1))
  }
}
